package com.sdx.console.wx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * @ClassName WxApi
 * @Description: 微信相关api方法
 * @author: tanbaocai
 * @date: 2018/8/8 11:08
 */
public class WxApi {
	private static final Logger log = LoggerFactory.getLogger("wx");


	public static String getAccessToken(String appid,String secret) throws IOException {
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;
		String response = HttpUtils.httpGet(url);
		/**
		 * { "access_token":"ACCESS_TOKEN",
		 "expires_in":7200,
		 }
		 */
		JSONObject jsonObject = JSON.parseObject(response);
		String accessToken = jsonObject.getString("access_token");
		return accessToken;
	}

	/**
	 * 小程序推送消息
	 * @param openId
	 * @param templateId
	 * @param page
	 * @param keyword1
	 * @param keyword2
	 * @param keyword3
	 * @param keyword4
	 * @return
	 */
	public static JSONObject wxPushMessage(String access_token, String openId, String formId, String templateId, String page,
                                           String keyword1, String keyword2, String keyword3, String keyword4, String keyword5) {
		JSONObject jsonObject = null;

		//组装微信推送信息
		WxMessage wxMessage = new WxMessage();
		wxMessage.setTouser(openId);
		wxMessage.setForm_id(formId);
		wxMessage.setTemplate_id(templateId);
		wxMessage.setPage(page);

		//组装业务信息
		Map<String,Object> m1 = new HashMap<>();
		Map<String,Object> m2 = new HashMap<>();
		Map<String,Object> m3 = new HashMap<>();
		Map<String,Object> m4 = new HashMap<>();
		Map<String,Object> m5 = new HashMap<>();
		Map<String,Object> mdata = new HashMap<String,Object>();

		m1.put("value", keyword1);
		m2.put("value", keyword2);
		m3.put("value", keyword3);
		m4.put("value", keyword4);


		mdata.put("keyword1",m1);
		mdata.put("keyword2",m2);
		mdata.put("keyword3",m3);
		mdata.put("keyword4",m4);

        if (!StringUtils.isEmpty(keyword5)) {
            m5.put("value", keyword5);
            mdata.put("keyword5",m5);
        }

		wxMessage.setData(mdata);
		try{
			//正式推送到用户

			String url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send" +
					"?access_token=" + access_token;
//			JSONObject ja =JSONObject.parseObject();
			String content = JSON.toJSONString(wxMessage);
			String responseEntity = HttpUtils.httpPost(url,content);
			log.info("小程序推送结果={}", responseEntity);
			jsonObject = JSON.parseObject(responseEntity);
		}catch (Exception ex){
			ex.printStackTrace();
			log.error("小程序推送失败");
		}
		return jsonObject;
	}


	public static void main(String[] args) throws DocumentException {

	}
}
